<template>
  <base-page-view class-name="page-container withdrawPage">
    <!-- <view v-if="typeState == 0" class="cardNo">
      <view class="leftText">
        <view>
          提现到银行卡
        </view>
        <view class="title1">{{ bankName || '' }}</view>
      </view>
      <view class="rightText" @click="toRealName">
        <view>修改银行卡</view>
        <image src="/static/images/mine/icon_my_more.png" class="icon_my_more" />
      </view>
    </view> -->
    <view v-if="typeState == 1" class="cardNo">
      <view class="leftText">
        <view>提现到支付宝</view>
        <view class="title1">{{ alipayAccount || '未绑定' }}</view>
      </view>
      <view class="rightText" @click="toAlipayName">
        <view>{{ alipayAccount ? '修改支付宝' : '绑定支付宝' }}</view>
        <image src="/static/images/mine/icon_my_more.png" class="icon_my_more" />
      </view>
    </view>
    <view v-if="typeState == 2" class="cardNo" @click="toAlipayName">
      <view class="leftText cloudAccount">
        <view class="alipayImg">
          <image v-if="applyCurrent.value == 'bankCard'" style="width: 62rpx;height: 38rpx;"
            :src="imgUrl+'/mine/yl.png'" mode="aspectFill"></image>
          <image v-if="applyCurrent.value == 'wechat'" style="width: 50rpx;height: 45rpx;" :src="imgUrl+'/mine/wx.png'"
            mode="aspectFill"></image>
          <image v-if="applyCurrent.value == 'alipay'" style="width: 50rpx;height: 51rpx;" :src="imgUrl+'/mine/zfb.png'"
            mode="aspectFill"></image>
        </view>
        <view class="alipayContent">
          <view v-if="applyCurrent">提现到{{applyCurrent.title}}</view>
          <view class="title1">{{ applyCurrent.account || '选择提现方式' }}</view>
        </view>
      </view>
      <view class="rightText">
        <view>{{ applyCurrent ? '更换提现方式' : '' }}</view>
        <image src="/static/images/mine/icon_my_more.png" class="icon_my_more" />
      </view>
    </view>
    <view class="content">
      <view class="title">提现金额</view>
      <view class="withdrawMoney">
        <view class="moneyIcon">￥</view>
        <input v-model="amount" placeholder="请输入您要提现的金额" placeholder-class="moneyInput" type="digit" @input="aaa" />
      </view>
      <view class="content_bottom">
        <view>可提现余额 ￥{{ validFee | formatMoney }}</view>
        <view class="all" @click="allWithdraw">全部提现</view>
      </view>
      <!-- <view class="btn" :class="{'submitBtn': !!amount}" @click="toWithdraw">
        提现
      </view> -->
      <b-button val="提现" @click="toWithdraw"></b-button>
    </view>
    <view class="tips">
      <view v-for="(title,index) in withdrawRuleDesc" :key="index" :class="{'title': index===0}">{{ title }}</view>
    </view>
    <view class="detailsBtn">
      <span @click="$navigateTo('/pagesCommission/bihs/withdrawDetails')">提现明细</span>
    </view>
    <code-popup ref="codePopup" :open="openState" :title="modeulTit" :phone="mobile" @engitBtn="engitBtn"
      @closeModul="closeModul" />
    <!-- 提现方式-->
    <base-popup :show="pShow" :show-close="false" type="bottom" :has-scroll="true" :mask="true" :mask-close="true"
      @close="closePopup">
      <uni-list>
        <view class="popup_head">
          <view class="title">提现方式</view>
          <view @click="closePopup">
            <image style="width: 34rpx;height: 34rpx;" :src="imgUrl+'/mine/popup_close.png'" mode=""></image>
          </view>
        </view>
        <radio-group @change="radioChange">
          <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in applyType" :key="item.value">
            <view v-if="item.show" class="radio_item">
              <b-checked :checked="item.value == applyCurrent.value&&item.account!=''" :disable="item.account==''"
                @checkedClick="checkedClick(item)"></b-checked>
              <uni-list-item :title="item.title"
                :note="item.account?item.account:item.value=='bankCard'?'银行卡未绑定':item.value=='wechat'?'微信未绑定':'支付宝未绑定'"
                showArrow>
                <template slot="header">
                  <image v-if="item.value == 'bankCard'" class="slot-image" style="width: 62rpx;height: 38rpx;"
                    :src="item.image" mode="aspectFill"></image>
                  <image v-if="item.value == 'wechat'" class="slot-image" style="width: 50rpx;height: 45rpx;"
                    :src="item.image" mode="aspectFill"></image>
                  <image v-if="item.value == 'alipay'" class="slot-image" style="width: 50rpx;height: 51rpx;"
                    :src="item.image" mode="aspectFill"></image>
                </template>
                <template slot="footer">
                  <view style="font-size: 26rpx;" @click="controlApplyType(item)">
                    {{!item.account?'去绑定':item.value=='bankCard'?'更换银行卡':item.value=='wechat'?'解除绑定':'更换支付宝'}}
                  </view>
                  <!-- </button> -->
                </template>
              </uni-list-item>
            </view>
          </label>
        </radio-group>
      </uni-list>
    </base-popup>
    <dealPassword ref="dealPassword" v-if="showDealPassword" @complete="completePassword" 
      @close="showDealPassword = false"></dealPassword>
  </base-page-view>
</template>

<script>
  import './withdraw.scss'
  // import { formatMoney } from '@utils/tools'
  import {
    formatMoney,
    debounce
  } from '@/utils/tools'
  import codePopup from '@/components/codePopup'
  import dealPassword from '@/components/pay/dealPassword'
  import { mapGetters } from 'vuex'
  export default {
    components: {
      codePopup,
      dealPassword
    },
    data() {
      return {
        applyType: [{
            value: 'alipay',
            title: '支付宝',
            image: `${process.env.VUE_APP_IMAGE_ASSET}/images/mine/zfb.png`,
            account: '',
            show: false
          },
          {
            value: 'wechat',
            title: '微信',
            image: `${process.env.VUE_APP_IMAGE_ASSET}/images/mine/wx.png`,
            account: '',
            show: false
          },
          {
            value: 'bankCard',
            title: '银行卡',
            image: `${process.env.VUE_APP_IMAGE_ASSET}/images/mine/yl.png`,
            account: '',
            show: false
          }
        ], //支付方式
        applyCurrent: "", //选中的支付方式
        pShow: false, //提现模态框状态
        imgUrl: `${process.env.VUE_APP_IMAGE_ASSET}/images/`,
        bankName: null,
        alipayName: null,
        alipayAccount: null,
        validFee: '',
        withdrawRuleDesc: '',
        amount: null,
        typeState: 1,
        transferChannel: '', //提现方式
        openState: false,
        modeulTit: '手机号验证',
        mobile: '',
        minFee: '',
        cloudAccountRes: {}, //云账户数据
        cloudAccountType: 0, //云账户类型
        withdrawInfo: {}, //提现用户信息
        lastTransferChannel: '',
        bindBankCard: false, //是否绑定银行卡
        showDealPassword: false
      }
    },
    computed: {
      ...mapGetters(['user'])
    },
    onShow() {
      var rolad = uni.getStorageSync('alipayRolad')
      if (rolad) {
        this.getAlipay()
      }
      this.app_interactive_data()
      this.pShow = false
    },
    onLoad(option) {
      //上次选择的支付方式
      this.withdrawInfo = uni.getStorageSync("withdrawInfo")
      console.log("this.withdrawInfo”", this.withdrawInfo)
      this.typeState = option.type == 'alipay' ? 1 : 2
      this.transferChannel = option.type
      // this.transferChannel = 'cloudBank'
      // this.typeState = 2
      if (this.typeState === 1) {
        this.getAlipay()
      }
    },
    onHide() {
      this.$refs.codePopup.smsCode = ''
    },
    methods: {
      app_interactive_data() {
        this.getData()
      },
      controlApplyType(item) {
        console.log("click", item)
        if (item.value == 'alipay') {
          let alipayBindFlag = false
          if (item.account != "" && item.account != null) {
            alipayBindFlag = true
          }
          this.$navigateTo('/pagesMine/certification/alipay?name=' + this.withdrawInfo.auth_name + '&account=' + item
            .account + '&alipayBindFlag=' + alipayBindFlag + '&withdrawType=' +
            this.typeState + '&auth_no=' + this.withdrawInfo.auth_no)
        } else if (item.value == 'wechat') {
          // #ifdef H5
          uni.showToast({
            title: '请到小程序操作',
            icon: 'none'
          })
          // #endif
          // #ifdef MP-WEIXIN
          if (item.account != "" && item.account != null) {
            this.$api.commissionApi.unbindWechatWithdraw({
              userId: this.userInfo.uid,
            }).then(res => {
              if (res.code == "000000") {
                this.getData()
                uni.setStorageSync("applyType", "")
                this.applyCurrent = ""
                uni.showToast({
                  title: '解绑成功!'
                })
              } else {
                uni.showToast({
                  title: '解绑失败!',
                  icon: 'none'
                })
              }
            })
            return
          }
          wx.getUserProfile({
            desc: '用于微信绑定', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (wx_res) => {
              if (wx_res.errMsg == 'getUserProfile:ok') {
                wx.login({
                  success: (res) => {
                    if (res.code) {
                      this.$api.commissionApi.openid({
                        jsCode: res.code
                      }).then(res => {
                        if (res.code == 0) {
                          this.$api.commissionApi.bindWechatWithdraw({
                            openId: res.data,
                            userId: this.userInfo.uid,
                            wechatName: wx_res.userInfo.nickName || this.userInfo.nickname
                          }).then(res => {
                            if (res.code == 0) {
                              this.getData()
                              uni.showToast({
                                title: '绑定成功!'
                              })
                            } else {
                              uni.showToast({
                                title: res.msg,
                                icon: "none"
                              })
                            }
                          })
                        } else {
                          uni.showToast({
                            title: '绑定失败!',
                            icon: 'none'
                          })
                        }
                      })
                    } else {
                      console.log('登录失败！' + res.errMsg)
                    }
                  }
                })
              }
            }
          })
          // #endif
        } else if (item.value == 'bankCard') {
          this.$navigateTo('/pagesMine/bindCard/bindBank?pageType=cloudAlipay&bindBankCard=' + this.bindBankCard)
        }
      },
      checkedClick(item) {
        if (item.account == '' || item.account == null || item.account == undefined) {
          uni.showToast({
            title: `你还未绑定${item.title}`,
            icon: "none"
          })
        } else {
          this.applyCurrent = item
          this.alipayAccount = item.account
          uni.setStorageSync("applyType", item.value)
          this.pShow = false
        }
      },
      radioChange(e) {
        console.log(e)
      },
      closePopup() {
        this.$set(this, 'pShow', false)
      },
      toRealName() {
        uni.removeStorageSync('realName')
        this.$navigateTo('/pagesMine/certification/index')
      },
      toAlipayName() {
        if (this.typeState == 2) {
          this.pShow = true
        } else if (this.typeState == 1) {
          let alipayBindFlag = false
          if (this.alipayAccount != "" && this.alipayAccount != null) {
            alipayBindFlag = true
          }
          this.$navigateTo('/pagesMine/certification/alipay?name=' + this.withdrawInfo.auth_name + '&account=' + this
            .alipayAccount + '&auth_no=' + this
            .withdrawInfo.auth_no + '&withdrawType=' +
            this.typeState + '&alipayBindFlag=' + alipayBindFlag)
        }
      },
      allWithdraw() {
        this.amount = formatMoney(this.validFee)
      },
      aaa(event) {
        setTimeout(() => {
          this.amount = event.target.value.match(/\d+(\.\d{0,2})?/) ? event.target.value.match(/\d+(\.\d{0,2})?/)[
            0] : ''
        }, 0)
      },
      async getData() {
        const res = await this.$api.commissionApi.getWithdrawInfo({
          userId: this.$store.state.userInfo.uid
        })
        const res1 = await this.$api.commissionApi.getBalanceWithdrawChannel({
          userId: this.$store.state.userInfo.uid
        })
        if (res.code === '000000') {
          if (res.data.userBankCard) {
            this.bankName = res.data.userBankCard.bank + '(' + res.data.userBankCard.cardNo.substring(res.data
              .userBankCard.cardNo.length - 4) + ')'
          }
          this.minFee = res.data.withdrawRule.minFee
          this.validFee = res.data.bihsCommissionAccount.validFee
          this.withdrawRuleDesc = res.data.withdrawRule.withdrawRuleDesc.split('\n') || ""
          if (this.typeState == 2) {
            this.cloudAccountType = res.data.withdrawRule.cloudAccountChannel.split(',') || ""
            for (let item in this.cloudAccountType) {
              this.applyType[this.cloudAccountType[item] - 1].show = true
            }
          }

          function filter(payType, obj) {
            let flag = false
            if (payType == 'alipay' && obj.bindAlipay) {
              flag = true
            } else if (payType == 'wechat' && obj.bindWechat) {
              flag = true
            } else if (payType == 'bankCard' && obj.bindBankCard) {
              flag = true
            }
            return flag
          }
          console.log("applyType", uni.getStorageSync('applyType'))
          this.lastTransferChannel = res.data.lastTransferChannel == 'cloudWechat' ? 'wechat' : res.data
            .lastTransferChannel == 'cloudAlipay' ? 'alipay' : 'bankCard'
          this.bindBankCard = res1.data.bindBankCard
          console.log('this.bindBankCard', res1.data)
          console.log('this.lastTransferChannel', this.lastTransferChannel)
          for (let item in this.applyType) {
            if (uni.getStorageSync('applyType') == this.applyType[item].value) {
              if (res1.code === '000000' && res1.data != null) {
                console.log("res1.data", res1.data)
                //判断是否存在此支付方式
                switch (uni.getStorageSync('applyType')) {
                  case 'alipay':
                    console.log("filter", filter('alipay', res1.data))
                    if (res.data.withdrawRule.cloudAccountChannel.indexOf("1") != -1 && filter('alipay', res1.data)) {
                      this.applyCurrent = this.applyType[item]
                    }
                    break
                  case 'wechat':
                    if (res.data.withdrawRule.cloudAccountChannel.indexOf("2") != -1 && filter('wechat', res1.data)) {
                      this.applyCurrent = this.applyType[item]
                    }
                    break
                  case 'bankCard':
                    if (res.data.withdrawRule.cloudAccountChannel.indexOf("3") != -1 && filter('bankCard', res1
                        .data)) {
                      this.applyCurrent = this.applyType[item]
                    }
                    break
                }
              }
              console.log("// this.applyCurrent", this.applyCurrent)
              console.log("lastTransferChannel", this.lastTransferChannel)
            } else if (this.lastTransferChannel == this.applyType[item].value && uni.getStorageSync('applyType') ==
              undefined || uni.getStorageSync('applyType') == "") {
              if (res1.code === '000000' && res1.data != null) {
                //是否绑定银行卡
                //用户上次提交的支付方式
                // console.log("lastTransferChannel1", this.lastTransferChannel)
                console.log("11", res.data.withdrawRule.cloudAccountChannel)
                switch (this.lastTransferChannel) {
                  case 'alipay':
                    console.log("filter", filter('alipay', res1.data))
                    if (res.data.withdrawRule.cloudAccountChannel.indexOf("1") != -1 && filter('alipay', res1.data)) {
                      this.applyCurrent = this.applyType[item]
                    }
                    break
                  case 'wechat':
                    if (res.data.withdrawRule.cloudAccountChannel.indexOf("2") != -1 && filter('wechat', res1.data)) {
                      this.applyCurrent = this.applyType[item]
                    }
                    break
                  case 'bankCard':
                    if (res.data.withdrawRule.cloudAccountChannel.indexOf("3") != -1 && filter('bankCard', res1.data)) {
                      this.applyCurrent = this.applyType[item]
                    }
                    break
                }
              }
            }
          }
        }
        if (res1.code === '000000' && res1.data != null) {
          this.cloudAccountRes = res1.data;
          if (res.data.withdrawRule.balanWithChannel == 2) {
            for (let item in this.applyType) {
              if (this.applyType[item].value == 'bankCard') {
                this.applyType[item].account = this.cloudAccountRes.bankCard
                this.applyType[item].key = res.data.withdrawRule.withdrawChannel.split(",")[2]
              } else if (this.applyType[item].value == 'wechat') {
                this.applyType[item].account = this.cloudAccountRes.wechatName
                this.applyType[item].key = res.data.withdrawRule.withdrawChannel.split(",")[0]
              } else if (this.applyType[item].value == 'alipay') {
                this.applyType[item].account = this.cloudAccountRes.alipayAccount
                this.applyType[item].key = res.data.withdrawRule.withdrawChannel.split(",")[1]
              }
            }
          } else if (res.data.withdrawRule.balanWithChannel == 1) {
            this.applyType[0].key = "alipay"
          }
        }
      },
      async getAlipay() {
        const res = await this.$api.commissionApi.getAlipay({
          userId: this.$store.state.userInfo.uid
        })
        if (res.code === 0) {
          this.alipayAccount = res.data.alipayAccount
          this.alipayName = res.data.alipayName
          this.mobile = res.data.mobile
        }
      },
      toWithdraw: debounce(async function() {
        if (this.typeState === 1 && !this.alipayAccount) {
          uni.showToast({
            title: '请先绑定支付宝',
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
        if (this.typeState == 2 && this.applyCurrent == "") {
          uni.showToast({
            title: '请先绑定提现方式',
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
        if (this.amount < this.minFee) {
          uni.showToast({
            title: `单笔提现申请需大于等于${this.minFee}元才可以提现`,
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
        if (this.amount > this.validFee) {
          uni.showToast({
            title: '可提现金额不足',
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
        if (!this.amount) {
          uni.showToast({
            title: '请输入提现金额',
            icon: 'none',
            duration: 3 * 1000
          })
          return false
        }
        if (this.transferChannel === 'alipay') {
          this.openState = true
          this.applyCurrent = this.applyType[0]
        } else {
          this.withdrawApply()
        }
      }, 300),
      async checkCode(code) {
        const res = await this.$api.commissionApi.getAlipyCheck({
          regionCode: '+86',
          smsCode: code
        })
        if (res.code === 0) {
          this.withdrawApply()
        }
      },
      // 获取加密公钥匙
      async getPublicKey() {
        let res = await this.$api.mineApi.tradePasswordGetPublicKey()
        if (res.code === 0) {
          this.publicKey = res.data
        }
      },
      // 交易密码输入完成
      async completePassword(str){
        await this.getPublicKey()
        // 加密, 提交
        let jse = new this.$jsEncrypt()
        jse.setPublicKey(this.publicKey)
        let encrypted = jse.encrypt(str)
        this.handleWithdrawApply(encrypted)
      },
      withdrawApply(){
        if(this.user && this.user.trade_password_flag!==1) {
          uni.showToast({
            title: "未设置密码，请先设置",
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            this.$navigateTo("/pagesMine/dealPassword/index")
          }, 2000);
          // this.$gc.$message({
          //   content: '您暂未设置交易密码，需设置交易密码后才可以使用',
          //   title: '温馨提示',
          //   type: 'richText',
          //   showMessage: true,
          //   showCancel: true,
          //   confirmText: '立即设置',
          //   align: 'center',
          //   confirm: () => {
          //     this.$navigateTo("/pagesMine/dealPassword/index")
          //   }
          // })
          return
        }
        this.showDealPassword = true
      },
      async handleWithdrawApply(password) {
        this.openState = false
        this.$api.commissionApi.withdrawApply({
          userId: this.$store.state.userInfo.uid,
          amount: this.amount,
          transferChannel: this.applyCurrent.key,
          alipayAccount: this.alipayAccount,
          alipayName: this.alipayName,
          nickName: this.$store.state.userInfo.nickname,
          realName: this.withdrawInfo.auth_name || '',
          idCard: this.withdrawInfo.auth_no || '',
          password: password
        }).then( apply =>{
          if (apply.code === '000000' || apply.code === 0) {
            this.showDealPassword = false
            let that = this;
            that.$navigateTo('/pagesCommission/bihs/withdrawSuccess')
          }
        }).catch(err=>{
          // 针对500的情况
          console.log('catch:', err)
          if(!err.code){
            uni.showToast({
              title: err.e.response && err.e.response.data ? err.e.response.data.message||err.e.response.data.msg : '服务器异常，请稍后再试',
              icon: 'none',
              duration: 3 * 1000
            })
            return
          }
          if(err.code === 1000002){
            this.showDealPassword = false
            this.$gc.$message({
              content: '超过6次错误, 交易密码已锁定, 请重置可解锁交易密码',
              title: '温馨提示',
              type: 'richText',
              showMessage: true,
              showCancel: true,
              confirmText: '重置交易密码',
              align: 'center',
              confirm: () => {
                this.$navigateTo("/pagesMine/dealPassword/index?status=1")
              }
            })
          } else {
            // 清除密码
            this.$refs.dealPassword.clearPassword()
            uni.showToast({
              title: err.msg || err.message || '服务器异常，请稍后再试',
              icon: 'none',
              duration: 3 * 1000
            })
          }
        })
      },
      engitBtn(code) {
        this.checkCode(code)
      },
      closeModul() {
        this.openState = false
      }
    }
  }
</script>
